using System.Runtime.InteropServices;
using System.IO;
using System.Text;


namespace 窗口程序开启控制台
{
    public partial class Form1 : Form
    {

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool AllocConsole();

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool FreeConsole();

        public Form1()
        {
            InitializeComponent();
        }

        private void OpenConsole()
        {
            if (!AllocConsole())
            {
                MessageBox.Show("无法分配控制台窗口。");
                return;
            }

            // 将标准输出重定向到控制台  
            StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())
            {
                AutoFlush = true
            };
            Console.SetOut(writer);
            Console.OutputEncoding = Encoding.UTF8; // 解决控制台乱码

            // 输出一些信息到控制台  
            Console.WriteLine("控制台窗口已打开！");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            OpenConsole();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            FreeConsole();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("输出到控制台");
        }
    }
}
